package org.baygo.view.api.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StopButtonActionListener implements ActionListener {
    private Logger log = LoggerFactory.getLogger(StopButtonActionListener.class);

    private JTextArea logArea;
    private JButton startButton;
    private JButton stopButton;

    public StopButtonActionListener() {
    }

    public StopButtonActionListener(JTextArea logArea, JButton startButton, JButton stopButton) {
        this.logArea = logArea;
        this.startButton = startButton;
        this.stopButton = stopButton;
    }

    public void actionPerformed(ActionEvent e) {
        SwingWorker<String, Boolean> server = new SwingWorker<String, Boolean>() {

            @Override
            protected String doInBackground() throws Exception {
                try {
                    StartButtonActionListener.getFileServer().closeServer();
                } catch (Exception e) {
                    log.error("", e);
                }
                publish(true);
                log.info("关闭服务");
                return "关闭服务";
            }

            @Override
            protected void process(List<Boolean> chunks) {
                log.info("process");
                for (Boolean result : chunks) {
                    if (result == true) {
                        logArea.append("[服务端]关闭服务成功!\n");
                        stopButton.setEnabled(false);
                        stopButton.setBackground(Color.gray);
                        startButton.setEnabled(true);
                        startButton.setText("启动服务");
                    }
                }
            }
        };
        server.execute();
    }

}